﻿'use strict';

var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();

// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
    getUserName();
});

// This function prepares, loads, and then executes a SharePoint query to get the current users information
function getUserName() {
    context.load(user);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}

// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess() {
    $('#message').text('Hello ' + user.get_title());
    //sendEmail("sharepoint.aig.com", user.get_email(), "Test email from SharePoint Rest API.", "Test email from SharePoint Rest API.");
}

// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
    alert('Failed to get user name. Error:' + args.get_message());
}

function sendEmail(from, to, body, subject) {

    var appweburl = decodeURIComponent(GetParameterByName('SPAppWebUrl'));
    var hostweburl = decodeURIComponent(GetParameterByName('SPHostUrl'));
    var urlTemplate = appweburl + "/_api/SP.Utilities.Utility.SendEmail";
    $.ajax({
        contentType: 'application/json',
        url: urlTemplate,
        type: "POST",
        data: JSON.stringify({
            'properties': {
                '__metadata': { 'type': 'SP.Utilities.EmailProperties' },
                'From': from,
                'To': { 'results': [to] },
                'Body': body,
                'Subject': subject
            }
        }
      ),
        headers: {
            "Accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            console.log('success')
        },
        error: function (err) {
            console.log(JSON.stringify(err));
        }
    });
}

function GetParameterByName(name) {
    try {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexString = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexString);
        var found = regex.exec(window.location.search);
        if (found == null) {
            return "";
        }
        return decodeURIComponent(found[1].replace(/\+/g, " "));
    } catch (e) {
        if (window.console) {
            console.log(e);
        }
        return "";
    }
}